package com.cyzy.controller;

import com.cyzy.dto.ApiResponse;
import com.cyzy.dto.ChatMessage;
import com.cyzy.dto.ChatSession;
import com.cyzy.service.AiService;
import com.cyzy.service.ChatSessionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 聊天会话控制器
 * @author LIGHT
 */
@RestController
@RequestMapping("/chat")
public class ChatSessionController {
    private static final Logger logger = LoggerFactory.getLogger(ChatSessionController.class);

    @Autowired
    private ChatSessionService chatSessionService;

    @Autowired
    private AiService aiService;

    /**
     * 创建新会话
     */
    @PostMapping("/sessions")
    public ResponseEntity<ApiResponse<ChatSession>> createSession(@RequestBody Map<String, String> request) {
        try {
            String userId = request.getOrDefault("userId", "anonymous");
            ChatSession session = chatSessionService.createSession(userId);
            return ResponseEntity.ok(ApiResponse.success("创建会话成功", session));
        } catch (Exception e) {
            logger.error("创建会话失败", e);
            return ResponseEntity.ok(ApiResponse.error("创建会话失败: " + e.getMessage()));
        }
    }

    /**
     * 获取会话详情
     */
    @GetMapping("/sessions/{sessionId}")
    public ResponseEntity<ApiResponse<ChatSession>> getSession(@PathVariable String sessionId) {
        try {
            ChatSession session = chatSessionService.getSession(sessionId);
            if (session == null) {
                return ResponseEntity.ok(ApiResponse.error(404, "会话不存在"));
            }
            return ResponseEntity.ok(ApiResponse.success(session));
        } catch (Exception e) {
            logger.error("获取会话详情失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取会话详情失败: " + e.getMessage()));
        }
    }

    /**
     * 获取用户所有会话
     */
    @GetMapping("/sessions")
    public ResponseEntity<ApiResponse<List<ChatSession>>> getUserSessions(@RequestParam(name = "userId") String userId) {
        try {
            if (userId == null || userId.trim().isEmpty()) {
                return ResponseEntity.ok(ApiResponse.error("用户ID不能为空"));
            }
            List<ChatSession> sessions = chatSessionService.getUserSessions(userId);
            return ResponseEntity.ok(ApiResponse.success(sessions));
        } catch (Exception e) {
            logger.error("获取用户会话列表失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取用户会话列表失败: " + e.getMessage()));
        }
    }

    /**
     * 更新会话标题
     */
    @PutMapping("/sessions/{sessionId}/title")
    public ResponseEntity<ApiResponse<ChatSession>> updateSessionTitle(
            @PathVariable(name = "sessionId") String sessionId,
            @RequestBody Map<String, String> request) {
        String title = request.get("title");
        if (title == null || title.trim().isEmpty()) {
            return ResponseEntity.ok(ApiResponse.error("会话标题不能为空"));
        }
        try {
            ChatSession session = chatSessionService.updateSessionTitle(sessionId, title);
            return ResponseEntity.ok(ApiResponse.success("更新标题成功", session));
        } catch (Exception e) {
            logger.error("更新会话标题失败", e);
            return ResponseEntity.ok(ApiResponse.error("更新会话标题失败: " + e.getMessage()));
        }
    }

    /**
     * 删除会话
     */
    @DeleteMapping("/sessions/{sessionId}")
    public ResponseEntity<ApiResponse<Map<String, Boolean>>> deleteSession(@PathVariable(name = "sessionId") String sessionId) {
        try {
            boolean success = chatSessionService.deleteSession(sessionId);
            Map<String, Boolean> response = new HashMap<>();
            response.put("success", success);
            if (success) {
                return ResponseEntity.ok(ApiResponse.success("删除会话成功", response));
            } else {
                return ResponseEntity.ok(ApiResponse.error(404, "会话不存在", response));
            }
        } catch (Exception e) {
            logger.error("删除会话失败", e);
            Map<String, Boolean> response = new HashMap<>();
            response.put("success", false);
            return ResponseEntity.ok(ApiResponse.error(500, "删除会话失败: " + e.getMessage(), response));
        }
    }

    /**
     * 发送消息并获取AI回复
     */
    @PostMapping("/sessions/{sessionId}/messages")
    public ResponseEntity<ApiResponse<Map<String, Object>>> sendMessage(
            @PathVariable(name = "sessionId") String sessionId,
            @RequestBody Map<String, String> request) {
        String content = request.get("content");
        if (content == null || content.trim().isEmpty()) {
            return ResponseEntity.ok(ApiResponse.error("消息内容不能为空"));
        }

        try {
            // 保存用户消息
            ChatMessage userMessage = new ChatMessage("user", content);
            chatSessionService.addMessage(sessionId, userMessage);

            // 获取AI回复
            Map<String, Object> aiResponse = aiService.chat(content);

            // 提取AI回复内容
            String aiContent = extractAiContent(aiResponse);

            // 保存AI回复
            ChatMessage aiMessage = new ChatMessage("assistant", aiContent);
            chatSessionService.addMessage(sessionId, aiMessage);

            // 构建响应
            Map<String, Object> response = new HashMap<>();
            response.put("userMessage", userMessage);
            response.put("aiMessage", aiMessage);

            return ResponseEntity.ok(ApiResponse.success("发送消息成功", response));
        } catch (Exception e) {
            logger.error("处理消息失败", e);
            return ResponseEntity.ok(ApiResponse.error("处理消息失败: " + e.getMessage()));
        }
    }

    /**
     * 获取会话的所有消息
     */
    @GetMapping("/sessions/{sessionId}/messages")
    public ResponseEntity<ApiResponse<List<ChatMessage>>> getSessionMessages(@PathVariable(name = "sessionId") String sessionId) {
        try {
            List<ChatMessage> messages = chatSessionService.getSessionMessages(sessionId);
            return ResponseEntity.ok(ApiResponse.success(messages));
        } catch (Exception e) {
            logger.error("获取会话消息失败", e);
            return ResponseEntity.ok(ApiResponse.error("获取会话消息失败: " + e.getMessage()));
        }
    }

    /**
     * 从AI响应中提取内容
     */
    @SuppressWarnings("unchecked")
    private String extractAiContent(Map<String, Object> aiResponse) {
        try {
            if (aiResponse.containsKey("choices")) {
                List<Map<String, Object>> choices = (List<Map<String, Object>>) aiResponse.get("choices");
                if (!choices.isEmpty()) {
                    Map<String, Object> choice = choices.get(0);
                    if (choice.containsKey("message")) {
                        Map<String, Object> message = (Map<String, Object>) choice.get("message");
                        if (message.containsKey("content")) {
                            return (String) message.get("content");
                        }
                    }
                }
            }

            // 如果无法从标准格式中提取，则尝试直接获取
            if (aiResponse.containsKey("content")) {
                return (String) aiResponse.get("content");
            }

            // 无法提取，返回空字符串或错误信息
            logger.warn("无法从AI响应中提取内容: {}", aiResponse);
            return "无法获取AI回复";
        } catch (Exception e) {
            logger.error("提取AI内容时出错", e);
            return "处理AI回复时出错";
        }
    }
} 